#pragma once 
#include <iostream>
#include <string>
#include <cstdarg>
#include <ctime>
#include <unistd.h>

#define LOG_NORMAL "log.txt"
#define LOG_ERROR "log.error"


#define DEBUG   0
#define NORMAL  1
#define WARNING 2
#define ERROR   3
#define FATAL   4

using namespace std;

enum { USAGE_ERR = 1,SOCKET_ERR,BIND_ERR,LISTEN_ERR};

const char* to_levelstring(int level)
{
    switch(level)
    {
        case DEBUG: return "DEBUG";
        case NORMAL: return "NORMAL";
        case WARNING: return "WARNING";
        case ERROR: return "ERROR";
        case FATAL: return "FATAL";
        default : return nullptr;
    }
}
void logMessage(int level,const char* format, ...)
{
    //[日志等级] [时间戳/时间] [pid] [错误信息]
    //[warning] [2023/5/20 9:00:01] [1234] [创建socket失败]

#define NUM 1024
    char logprefix[NUM];
    snprintf(logprefix,sizeof(logprefix),"[%s][%ld][pid:%d]",
        to_levelstring(level),(long int)time(nullptr),getpid());

    char logcontent[NUM];
    va_list arg;
    va_start(arg,format);
    vsnprintf(logcontent,sizeof(logcontent),format,arg);

    // cout << logprefix << logcontent << endl;

    //向文件里写日志
    FILE* log = fopen(LOG_NORMAL,"a");
    FILE* err = fopen(LOG_ERROR,"a");
    if(log != nullptr && err != nullptr)
    {
        FILE* cur = nullptr;
        if(level == DEBUG || level == NORMAL || level == WARNING)
            cur = log;
        if(level == ERROR || level ==FATAL)
            cur = err;
        fprintf(cur,"%s%s\n",logprefix,logcontent);
        fclose(log);
        fclose(err);
    }
    

}